﻿using COSXML;
using COSXML.Common;
using COSXML.Model.Object;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Simple.Contracts.Contracts;
using Simple.Contracts.Models;
using Simple.Contracts.Models.Common;
using Simple.Repository;
using Simple.Repository.SimpleEntitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Simple.Common.Extensions;
using Microsoft.Extensions.Configuration;

namespace Simple.Services.Services
{
    public class FileService : BaseService, IFileService
    {
        private readonly string _tencentCloudCosBucket;
        private readonly string _tencentCloudCosBucketDomin;
        private readonly CosXmlServer _tencentCloudCosXmlServer;
        public FileService(
            IConfiguration configuration, 
            FreeSqlCloud freeSqlCloud, 
            CurrentAccount currentAccount,
            CosXmlServer tencentCloudCosXmlServer) : base(freeSqlCloud, currentAccount)
        {
            _tencentCloudCosBucket = configuration["TencentCloud:CosBucketName"]!;
            _tencentCloudCosBucketDomin= configuration["TencentCloud:CosBucketDomin"]!;
            _tencentCloudCosXmlServer = tencentCloudCosXmlServer;
        }


        public async Task<Result<UploadImageDto>> UploadImage(string fileTag, IFormFile file)
        {
            double fileSize = Math.Ceiling(((file.Length / 1024.0) / 1024.0) * 100) / 100;
            var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            var fileName = $"{Guid.NewGuid().ToString("N")}{fileExtension}";
            var bytes = await file.ToByteArrayAsync();
            var cosPath = $"uploads/com{_currentAccount.CompanyId}/{DateTime.Now.ToString("yyyyMM")}/{fileName}";
            PutObjectRequest putObjectRequest = new PutObjectRequest(_tencentCloudCosBucket, cosPath, bytes);
            PutObjectResult result = _tencentCloudCosXmlServer.PutObject(putObjectRequest);

            var fileUrl = $"{_tencentCloudCosBucketDomin}/{cosPath}";
            var fileEntity = new Repository.SimpleEntitys.CompanyFile()
            {
                CreateTime = DateTime.Now,
                FileTag = fileTag,
                FileUrl = fileUrl,
                FileSize = fileSize,
                CreateBy = _currentAccount.EmployeeId,
                CompanyId = _currentAccount.CompanyId,
                FileExtension = fileExtension,
                FileDurationSecond = 0,
                IsDelete = 0
            };
            var fileId = await _simpleFreeSql.Insert<Simple.Repository.SimpleEntitys.CompanyFile>(fileEntity).ExecuteIdentityAsync();
            var data = new UploadImageDto()
            {
                fileId = fileId,
                fileUrl = fileUrl
            };
            return Result<UploadImageDto>.Success(data);
        }

        /// <summary>
        /// 上传MP3
        /// </summary>
        /// <param name="fileType"></param>
        /// <param name="durationSecond"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<Result<UploadMp3Dto>> UploadMp3(string fileTag, double durationSecond, IFormFile file)
        {
            double fileSize = Math.Ceiling(((file.Length / 1024.0) / 1024.0) * 100) / 100;
            var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            var fileName = $"{Guid.NewGuid().ToString("N")}{fileExtension}";
            var bytes = await file.ToByteArrayAsync();
            var cosPath = $"uploads/com{_currentAccount.CompanyId}/{DateTime.Now.ToString("yyyyMM")}/{fileName}";
            PutObjectRequest putObjectRequest = new PutObjectRequest(_tencentCloudCosBucket, cosPath, bytes);
            PutObjectResult result = _tencentCloudCosXmlServer.PutObject(putObjectRequest);

            var fileUrl = $"{_tencentCloudCosBucketDomin}/{cosPath}";
            var fileEntity = new Repository.SimpleEntitys.CompanyFile()
            {
                CreateTime = DateTime.Now,
                FileTag = fileTag,
                FileUrl = fileUrl,
                FileSize = fileSize,
                CreateBy = _currentAccount.EmployeeId,
                CompanyId = _currentAccount.CompanyId,
                FileDurationSecond = durationSecond,
                FileExtension = fileExtension,
                IsDelete = 0
            };
            var fileId = await _simpleFreeSql.Insert<Simple.Repository.SimpleEntitys.CompanyFile>(fileEntity).ExecuteIdentityAsync();
            var data = new UploadMp3Dto()
            {
                fileId = fileId,
                fileUrl = fileUrl,
                durationSecond = durationSecond,
                mp3Text = string.Empty
            };
            return Result<UploadMp3Dto>.Success(data);
        }
    }
}
